package com.hzc.springchan.service.impl.business;

import com.hzc.springchan.bean.exception.CException;
import com.hzc.springchan.bean.request.Request;
import com.hzc.springchan.bean.response.Response;
import com.hzc.springchan.constant.System;
import com.hzc.springchan.enums.PrivError;
import com.hzc.springchan.enums.PubError;
import com.hzc.springchan.enums.impl.EmsBusiness;
import com.hzc.springchan.service.IBusinessService;
import com.hzc.springchan.service.IVerifyCodeService;
import com.hzc.springchan.util.LogUtils;
import com.hzc.springchan.util.RandUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * @Description: 验证码发送业务类
 * @Author: chen990627
 * @Date: 2022/11/01
 **/
@Service(System.ApiBusinessName.SEND_CODE)
public class SendCodeBusiness implements IBusinessService<Request, Response> {

    @Autowired
    @Qualifier(System.VerifyCodeBean.EMS)
    private IVerifyCodeService emsVerifyCodeService;

    @Override
    public void doBusiness(Request request, Response response) {

        request.put("receiver", request.get("userName"));
        request.put("verifyCode", RandUtils.randStr(6, true));
        request.put("business", findBusiness(((String) request.get("business"))));

        IVerifyCodeService.VerifyResponse sendResponse = emsVerifyCodeService.sendCode(request);
        if (!sendResponse.isSuccess()) {
            response.setError(PubError.EMSCODE_SEND_ERROR);
            return;
        }
    }

    private EmsBusiness findBusiness(String business) {
        for (EmsBusiness emsBusiness : EmsBusiness.values()) {
            if (business.equals(emsBusiness.businessName())) {
                return emsBusiness;
            }
        }
        LogUtils.info(this, "emsBusiness not found: {}", business);
        throw new CException(PrivError.CPARAM_CHECK_FAILED);
    }
}
